<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "z_region".
 *
 * @property int $code 地区代码
 * @property int $p_code 上级地区代码
 * @property string $name 区域名称
 */
class ZRegion extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'z_region';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['code'], 'required'],
            [['code', 'p_code'], 'integer'],
            [['name'], 'string', 'max' => 60],
            [['code'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'code' => 'Code',
            'p_code' => 'P Code',
            'name' => 'Name',
        ];
    }

    public static function getTree()
    {
        $province = self::find()
            ->orderBy(['code' => SORT_ASC])
            ->where(['p_code' => 0])
            ->select(['code as value', 'name as text'])
            ->asArray()
            ->all();

        foreach ($province as &$p) {
            $p['children'] = self::find()
                ->orderBy(['code' => SORT_ASC])
                ->where(['p_code' => $p['value']])
                ->select(['code as value', 'name as text'])
                ->asArray()
                ->all();

            foreach ($p['children'] as &$c) {
                $c['children'] = self::find()
                    ->orderBy(['code' => SORT_ASC])
                    ->where(['p_code' => $c['value']])
                    ->select(['code as value', 'name as text'])
                    ->asArray()
                    ->all();
            }
        }

        return $province;
    }
}
